package zut.wework;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencentcloudapi.wemeet.client.LiveClient;
import com.tencentcloudapi.wemeet.client.MeetingClient;
import com.tencentcloudapi.wemeet.client.RecordingClient;
import com.tencentcloudapi.wemeet.client.UserClient;
import com.tencentcloudapi.wemeet.common.RequestSender;
import com.tencentcloudapi.wemeet.common.constants.InstanceEnum;
import com.tencentcloudapi.wemeet.common.exception.WemeetSdkException;
import com.tencentcloudapi.wemeet.common.profile.HttpProfile;
import com.tencentcloudapi.wemeet.models.*;
import com.tencentcloudapi.wemeet.models.live.ModifyLiveByIdRequest;
import com.tencentcloudapi.wemeet.models.live.QueryLiveReplayByCodeRequest;
import com.tencentcloudapi.wemeet.models.live.QueryLiveReplayResponse;
import com.tencentcloudapi.wemeet.models.meeting.*;
import com.tencentcloudapi.wemeet.models.recording.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.Test;
import zut.wework.utils.MeetingUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>会议请求</p>
 * 企业内部应用鉴权方式
 * 1.企业管理员登录腾讯会议官网（https://meeting.tencent.com/），
 * 单击右上角【用户中心】，在左侧菜单栏中的【企业管理】>【高级】>【restApi】中进行查看。
 * 2.支持两种方式实例化请求代理对象
 * 1）全局代理对象：设置全局HttpProfile，在项目启动时进行初始化，并构造RequestSender对象，所有客户端请求可共用一套配置；
 * 2）局部代理对象：也可以针对具体某个接口单独实例化HttpProfile，并通过此对象构造RequestSender对象
 * 3.构造具体client，参考client包，例如MeetingClient，通过构造方法传入RequestSender实例，初始化client
 * 4.通过client调用具体方法即可发起请求，
 * eg：QueryMeetingDetailResponse response = client.createMeeting(request);
 * <p>
 * 第三方应用鉴权（OAuth2.0）
 * 1.参考官网文档（https://cloud.tencent.com/document/product/1095/51257）获取AccessToken和OpenId
 * 2.参考【企业内部应用鉴权方式】第2步，初始化代理实例
 * 3.构造请求体，并添加第1部申请到的参数到请求Header中
 * eg:
 * CreateMeetingRequest request = new CreateMeetingRequest();
 * request.setUserId("test_user");
 * request.setInstanceId(InstanceEnum.INSTANCE_MAC.getInstanceID());
 * request.setSubject("sdk 创建会议");
 * request.setType(0);
 * request.setStartTime("1619733600");
 * request.setEndTime("1619737200");
 * // 设置Header
 * request.addHeader(ReqHeaderConstants.ACCESS_TOKEN, "111111");
 * request.addHeader(ReqHeaderConstants.OPEN_ID, "2222");
 * 4.通过client发起请求
 *
 * @author tencent
 * @date 2021/4/29
 */
public class MeetingRequest {
    private static final Log log = LogFactory.getLog(MeetingRequest.class);
    // 初始化全局client
    /**
     * 初始化全局会议client
     */
    public static final MeetingClient MEETING_CLIENT;
    /**
     * 初始化全局用户client
     */
    private static final UserClient USER_CLIENT;
    private static final LiveClient LIVE_CLIENT;
    private static final RecordingClient RECORDING_CLIENT;
    private static final Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();

    static {
        HttpProfile profile = new HttpProfile();
        // 腾讯会议分配给三方开发应用的 App ID。企业管理员可以登录 腾讯会议官网，单击右上角【用户中心】
        // 在左侧菜单栏中的【企业管理】>【高级】>【restApi】中进行查看。
        profile.setAppId("210984532");
        // 用户子账号或开发的应用 ID，企业管理员可以登录 腾讯会议官网，单击右上角【用户中心】
        // 在左侧菜单栏中的【企业管理】>【高级】>【restApi】中进行查看（如存在 SdkId 则必须填写，早期申请 API 且未分配 SdkId 的客户可不填写）。
        profile.setSdkId("19370190646");
        // 请求域名
        profile.setHost("https://api.meeting.qq.com");
        // 申请的安全凭证密钥对中的 SecretId，传入请求header，对应X-TC-Key
        profile.setSecretId("zvF4VEcdwlcG9bfyPCkF5xQDIYw8LdNj");
        // 申请的安全凭证密钥对中的 Secretkey，用户签名计算
        profile.setSecretKey("rROP64FlucdPp8kHNP1vyxhMNV7eItBsGOoCCxQzkU7nRtNK");
        // 是否开启请求日志，开启后会打印请求和返回的详细日志
        profile.setDebug(true);
        // 设置请求超时时间，单位s
        profile.setReadTimeout(3);
        // 设置获取连接超时时间，单位s
        profile.setConnTimeout(1);

        // 初始化全局sender，也可以方法级别实例化
        RequestSender sender = new RequestSender(profile);
        // 自定义拦截器，可以忽略
        /*
        sender.addInterceptors(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                // TODO return null; 用户自定义实现
                return chain.proceed(chain.request());
            }
        });
        */
        // 实例化client
        MEETING_CLIENT = new MeetingClient(sender);
        USER_CLIENT = new UserClient(sender);
        LIVE_CLIENT = new LiveClient(sender);
        RECORDING_CLIENT = new RecordingClient(sender);


        // ...
    }

    /**
     * 通过创建会议
     *
     * @return Json格式的response
     * @throws WemeetSdkException
     */
    @Test
    public void CreateMeetingTest() throws WemeetSdkException {
        CreateMeetingRequest request = new CreateMeetingRequest();
        request.setUserId("201928034202");
        request.setInstanceId(InstanceEnum.INSTANCE_MAC.getInstanceID());
        request.setSubject("测试会议001");
        User user = new User();
        user.setUserId("201928034202");
        List<User> hosts = new ArrayList<>();
        hosts.add(user);
        request.setHosts(hosts);//主持人
        List<String> ids = Arrays.asList("201928034202", "201928034230");
        request.setInvitees(MeetingUtil.idsToUserList(ids));//邀请列表
        request.setType(0);//会议类型：0：预约会议 1：快速会议
//        request.setEnableLive(true);
//        LiveConfig liveConfig = new LiveConfig();
//        liveConfig.setLiveSubject("测试");
//        liveConfig.setLiveSummary("Hello World!");
//        liveConfig.setEnableLiveIm(true);
//        liveConfig.setEnableLiveReplay(true);
//        request.setLiveConfig(liveConfig);
        // OAuth2.0鉴权方式，PROFILE对象不用设置sdkId、appId、secretID、secretKey
        // request.addHeader(ReqHeaderConstants.ACCESS_TOKEN, "111111");
        // request.addHeader(ReqHeaderConstants.OPEN_ID, "2222");
        request.setStartTime(String.valueOf(MeetingUtil.getLongStamp() + 60));
        request.setEndTime(String.valueOf(MeetingUtil.getLongStamp() + 6060));
        MeetingSetting setting = new MeetingSetting();
        setting.setAutoRecordType("cloud");
        request.setSettings(setting);
        // 非注册用户设置
        // request.addHeader(ReqHeaderConstants.REGISTERED, "0");
        request.setMeetingType(1);
        RecurringRule rules = new RecurringRule();
        rules.setRecurringType(2);
        rules.setUntilType(1);//0为日期结束 需指定until_date  1为次数结束 需指定until_count
        rules.setUntilCount(2);
        request.setRecurringRule(rules);
        QueryMeetingDetailResponse response = MEETING_CLIENT.createMeeting(request);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(response));

    }

    /**
     * 查userid的会议
     */
    @Test
    public void queryUserMeetingTest() throws WemeetSdkException {
        QueryUserMeetingsRequest request = new QueryUserMeetingsRequest();
        request.setInstanceId(1);
        request.setUserId("201928034202");
        QueryUserMeetingsResponse response = MEETING_CLIENT.queryUserMeetings(request);
        System.out.println(GSON.toJson(response));
    }

    @Test
    public void queryMeetingByCodeTest() throws WemeetSdkException {
        QueryMeetingByCodeRequest request = new QueryMeetingByCodeRequest();
        request.setInstanceId(1);
        request.setMeetingCode("813284567");
        request.setUserId("201928034202");
        QueryMeetingDetailResponse response = MEETING_CLIENT.queryMeetingByCode(request);
        System.out.println(GSON.toJson(response));

    }

    /**
     * 通过MeetingId取消
     *
     * @return Json格式的response
     * @throws WemeetSdkException
     */
    @Test
    public void cancelMeetingTest() throws WemeetSdkException {
        CancelMeetingRequest cancelMeetingRequest = new CancelMeetingRequest();
        cancelMeetingRequest.setMeetingId("7522281929027401172");
        cancelMeetingRequest.setUserId("201928034202");
        cancelMeetingRequest.setInstanceId(1);
        cancelMeetingRequest.setReasonCode(0);
        BaseResponse response = MEETING_CLIENT.cancelMeeting(cancelMeetingRequest);
        log.info(GSON.toJson(response));
        System.out.println(GSON.toJson(response));
    }

    /**
     * 通过MeetingId查询
     *
     * @return Json格式的response
     * @throws WemeetSdkException
     */
    @Test
    public void queryMeetingTest() throws WemeetSdkException {
        QueryMeetingByIdRequest queryMeetingByIdRequest = new QueryMeetingByIdRequest();
        queryMeetingByIdRequest.setMeetingId("6650191169005266031");
        queryMeetingByIdRequest.setInstanceId(1);
        queryMeetingByIdRequest.setUserId("meeting205271");
        QueryMeetingDetailResponse response = MEETING_CLIENT.queryMeetingById(queryMeetingByIdRequest);
        System.out.println(GSON.toJson(response));
    }

    /**
     * 申请录播
     */
    @Test
    public void modifyMeetingById() throws WemeetSdkException {
        ModifyLiveByIdRequest request = new ModifyLiveByIdRequest();
        request.setMeetingId("6650191169005266031");
        request.setInstanceId(1);
        request.setUserId("meeting205271");
        LiveConfig liveConfig = new LiveConfig();
        liveConfig.setEnableLiveReplay(true);
        liveConfig.setLiveSubject("zzy的直播测试");
        liveConfig.setLiveSummary("HelloWorld!");
        liveConfig.setEnableLiveIm(true);
        request.setLiveConfig(liveConfig);
        BaseResponse baseResponse = LIVE_CLIENT.modifyConfigByMeetingId(request);
        System.out.println(GSON.toJson(baseResponse));
    }

    /**
     * 修改会议的直播选项
     */
    @Test
    public void ModifyMeetingConfigTest() throws WemeetSdkException {
        ModifyMeetingRequest request = new ModifyMeetingRequest();
        MeetingSetting setting = new MeetingSetting();
        request.setMeetingId("6650191169005266031");
        request.setUserId("meeting205271");
        request.setInstanceId(1);
        setting.setMuteEnableJoin(true);
        request.setEnableLive(true);
        setting.setAutoRecordType("cloud");
        request.setSettings(setting);
        QueryMeetingDetailResponse response = MEETING_CLIENT.modifyMeeting(request);
        System.out.println(GSON.toJson(response));
    }

    @Test
    public void queryLiveTest() throws WemeetSdkException {
        QueryLiveReplayByCodeRequest request = new QueryLiveReplayByCodeRequest();
        request.setMeetingCode("317385478");
        request.setInstanceId(1);
        request.setUserId("201928034202");
        QueryLiveReplayResponse replayResponse = LIVE_CLIENT.queryLiveReplaysByMeetingCode(request);
        System.out.println(GSON.toJson(replayResponse));
    }

    /**
     * 查看录制情况
     */

    @Test
    public void testRecords() throws WemeetSdkException {
        QueryRecordsRequest request = new QueryRecordsRequest();
        request.setUserId("201928034202");
        int startTime = Math.toIntExact(MeetingUtil.getLongStamp() - 48 * 60 * 60);
        request.setStartTime(startTime);
        request.setEndTime(startTime + 120 * 60 * 60);
        request.setMeetingId("10624032964331755563");
        QueryRecordsResponse queryRecordsResponse = RECORDING_CLIENT.queryRecords(request);
        List<QueryRecordsResponse.MeetingRecord> records = queryRecordsResponse.getRecords();
    }

    @Test
    public void testFile() throws WemeetSdkException {
        QueryFileAddressRequest request = new QueryFileAddressRequest();
        request.setRecordFileId("1527956691495223297");
        request.setUserId("201928034202");
        QueryFileAddressResponse queryFileAddressResponse = RECORDING_CLIENT.queryRecordFileAddress(request);
        System.out.println(GSON.toJson(queryFileAddressResponse));
    }

    @Test
    public void testModifySetting() throws WemeetSdkException {
        ModifyRecordsSettingRequest request = new ModifyRecordsSettingRequest();
        request.setMeetingId("10624032964331755563");
        request.setMeetingRecordId("1527956691495223296");
        request.setUserId("201928034202");
        ModifyRecordsSettingRequest.SharingConfig config = new ModifyRecordsSettingRequest.SharingConfig();
        config.setAllowDownload(true);
        request.setSharingConfig(config);
        BaseResponse baseResponse = RECORDING_CLIENT.modifyRecordsSetting(request);
        System.out.println(GSON.toJson(baseResponse));
    }

}